import ROSLIB from "roslib";

/**
 * 为参数的Ros对象添加一个新的相机订阅主题对象，返回该主题对象
 * @param { ROSLIB.Ros } roslink 
 */
function createNewCameTopic(roslink = null) {
  if (roslink == null) {
    console.log("error in camera.js: ros is null!");
    return;
  }
  var ros = roslink;

  var rviz_stream = new ROSLIB.Topic({
    ros: ros,
    name: "/usb_cam/image_raw/compressed",
    messageType: "sensor_msgs/CompressedImage",
  });
  console.log(rviz_stream.name);
  return rviz_stream;
}

/**
 * 使获得的订阅主题进行订阅行为，并调用回调函数
 * @param { ROSLIB.Topic } topic 
 * @param { function } callback 回调函数的首个参数即是订阅的返回信息
 */
function subscribeTopic(topic, callback) {
  topic.subscribe(function (msg) {
    // console.log(msg);
    callback(msg);
  });
}

/**
 * 向目标Ros对象发出打开相机的命令
 * @param { ROSLIB.Ros } roslink 
 */
function openCamera(roslink = null) {
  try {
    var camClient = new ROSLIB.Service({
      ros: roslink,
      name: "/add_two_ints",
      serviceType: "rospy_tutorials/AddTwoInts",
    });
    // open
    var request = new ROSLIB.ServiceRequest({
      name: "cam",
      a: 1,
      p: "s",
    });

    camClient.callService(request, function (result) {
      console.log(
        "Result for service call on " + camClient.name + ": " + result.feedback
      );
      return result.feedback;
    });
  } catch(error) {
    console.log("apply Camera error");
    console.log(error);
  }
}

/**
 * 向目标Ros对象发出关闭相机的命令
 * @param { ROSLIB.Ros } roslink 
 */
function closeCamera(roslink = null) {
  try {
    var camClient = new ROSLIB.Service({
      ros: roslink,
      name: "/add_two_ints",
      serviceType: "rospy_tutorials/AddTwoInts",
    });
    // close
    var request = new ROSLIB.ServiceRequest({
      name: "cam",
      a: 0,
      p: "s",
    });

    camClient.callService(request, function (result) {
      console.log(
        "Result for service call on " + camClient.name + ": " + result.feedback
      );
      console.log(result.feedback);
      return result.feedback;
    });
  } catch (error) {
    console.log(error)
  }
}

/**
 * 断开目标相机主题对象的连接
 * @param { ROSLIB.Topic } topic 
 */
function destroyTopic(topic) {
  topic.unsubscribe();
  topic = null;
}

export { createNewCameTopic, subscribeTopic, openCamera, closeCamera, destroyTopic };
